<template>
  <div class="app-container">
    <!-- 1. 课程调整申请标题 -->
    <div class="mb-6">
      <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800 mb-2">
        课程调整申请
      </h2>
      <p class="text-gray-500">
        教师因临时有事或外出学习等情况，可在此选择课程并提交调整申请
      </p>
    </div>

    <!-- 2. 课程选择区域 -->
    <el-card shadow="hover" class="mb-6 transition-all duration-300 hover:shadow-md">
      <h3 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
        <i class="el-icon-schedule mr-2 text-primary"></i>选择需要调整的课程
      </h3>

      <!-- 搜索和筛选 -->
      <div class="flex flex-col md:flex-row md:items-center justify-between mb-6 gap-4 p-2 bg-gray-50 rounded-lg">
        <div class="relative flex-grow max-w-md">
          <el-input
              placeholder="搜索课程名称、课程代码..."
              prefix-icon="Search"
              class="w-full"
              v-model="searchKeyword"
              @input="handleSearch"
          ></el-input>
        </div>
        <div class="flex flex-wrap gap-3">
          <el-select
              placeholder="全部学期"
              class="min-w-[140px]"
              v-model="selectedSemester"
              @change="handleFilterChange"
          >
            <el-option label="2023-2024学年 第一学期" value="2023-1"></el-option>
            <el-option label="2023-2024学年 第二学期" value="2023-2"></el-option>
            <el-option label="2024-2025学年 第一学期" value="2024-1"></el-option>
            <el-option label="2024-2025学年 第二学期" value="2024-2"></el-option>
            <el-option label="2025-2026学年 第一学期" value="2025-1"></el-option>
            <el-option label="2025-2026学年 第二学期" value="2025-2"></el-option>
          </el-select>
        </div>
      </div>

      <!-- 课程列表表格 -->
      <el-table
          :data="filteredCourseList"
          border
          stripe
          :header-cell-style="{background: '#f5f7fa'}"
          class="mb-4 transition-all duration-300"
          v-loading="tableLoading"
          element-loading-text="加载中..."
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="课程信息" min-width="220">
          <template #default="scope">
            <div class="flex items-center">
              <div class="w-10 h-10 rounded bg-primary/10 flex items-center justify-center text-primary mr-3">
                <i class="el-icon-book"></i>
              </div>
              <div>
                <p class="font-medium">{{ scope.row.courseName }}</p>
                <p class="text-sm text-gray-500">{{ scope.row.courseId }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="班级名称" prop="className" min-width="180"></el-table-column>
        <el-table-column label="学年学期" min-width="160">
          <template #default="scope">
            <div>
              <p>{{ scope.row.academicYear }}</p>
              <p class="text-sm text-gray-500">{{ scope.row.semesterText }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="上课时间" min-width="180">
          <template #default="scope">
            <div>
              <p>
                <span class="inline-block w-16">{{ getWeekDay(scope.row.weekDay) }}</span>
                <span>{{ scope.row.startTime }}-{{ scope.row.endTime }}</span>
              </p>
              <p class="text-sm text-gray-500">
                {{ scope.row.weekType === 2 ? '单周' : scope.row.weekType === 4 ? '双周' : '每周' }}
              </p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="上课教室" prop="classroom" min-width="140"></el-table-column>
        <el-table-column label="选课情况" min-width="160">
          <template #default="scope">
            <div>
              <p>{{ scope.row.currentEnrollment }}/{{ scope.row.maxCapacity }}人</p>
              <div class="flex items-center">
                <el-progress
                    :percentage="scope.row.enrollmentRate"
                    :stroke-width="6"
                    :show-text="false"
                    class="w-24 mt-1"
                ></el-progress>
                <span class="text-xs text-gray-500 ml-2">{{ scope.row.enrollmentRate }}%</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="学院" prop="department" min-width="140"></el-table-column>
        <el-table-column label="状态" min-width="100">
          <template #default="scope">
            <el-tag
                :type="scope.row.status === 1 ? 'success' : 'warning'"
                :disable-transitions="false"
            >
              {{ scope.row.status === 1 ? '正常' : '已调整' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="140">
          <template #default="scope">
            <el-button
                link
                text-color="#165DFF"
                @click="selectCourse(scope.row)"
                class="mr-2 hover:text-primary/80 transition-colors"
            >
              选择
            </el-button>
            <el-button
                link
                text-color="#6B7280"
                @click="showCourseDetail(scope.row)"
                class="hover:text-gray-700 transition-colors"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 无数据状态 -->
      <div v-if="!tableLoading && filteredCourseList.length === 0" class="text-center py-8">
        <el-empty description="未找到匹配的课程数据"></el-empty>
      </div>

      <!-- 课程选择分页 -->
      <div class="flex items-center justify-between mt-6" v-if="filteredCourseList.length > 0">
        <div class="text-sm text-gray-500">显示 {{ (courseCurrentPage-1)*coursePageSize + 1 }}-{{ Math.min(courseCurrentPage*coursePageSize, total) }} 条，共 {{ total }} 条</div>
        <el-pagination
            v-model:current-page="courseCurrentPage"
            :page-size="coursePageSize"
            :page-sizes="[5, 10, 20]"
            :total="total"
            layout="prev, pager, next, jumper, sizes"
            @size-change="handleCourseSizeChange"
            @current-change="handleCourseCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 3. 课程调整申请表单区域 -->
    <div v-if="selectedCourse" class="adjust-container mb-6">
      <!-- 原课程信息 -->
      <el-row class="mb-6">
        <el-col :span="24">
          <el-card shadow="hover">
            <div class="form-section">
              <h4 class="section-title">原课程信息</h4>
              <el-row :gutter="20" class="mb-2">
                <el-col :span="6">
                  <el-form-item label="课程名称">
                    <el-input :value="selectedCourse.courseScheduleDetails?.className" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="班级名称">
                    <el-input :value="selectedCourse.courseScheduleDetails?.className" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="学年学期">
                    <el-input
                        :value="`${selectedCourse.courseScheduleDetails?.academicYear || '2025'}-${selectedCourse.courseScheduleDetails?.semester || '1'}学期`"
                        disabled
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="课程类型">
                    <el-input :value="selectedCourse.courseScheduleDetails?.courseType || '未知'" disabled></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" class="mb-2">
                <el-col :span="6">
                  <el-form-item label="上课时间">
                    <el-input :value="getOriginalTimeText()" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="上课教室">
                    <el-input :value="selectedCourse.courseScheduleDetails?.classroom" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="上课周次">
                    <el-input
                        :value="`第${selectedCourse.courseScheduleDetails?.startWeek}-${selectedCourse.courseScheduleDetails?.endWeek}周`"
                        disabled
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="单双周">
                    <el-input
                        :value="selectedCourse.courseScheduleDetails?.weekType === 2 ? '单周' : selectedCourse.courseScheduleDetails?.weekType === 4 ? '双周' : '每周'"
                        disabled
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item label="授课教师">
                    <el-input :value="getTeacherName(selectedCourse.courseScheduleDetails?.teacherId)" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="总学时">
                    <el-input :value="selectedCourse.courseScheduleDetails?.coursePeriod" disabled></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="班级容量">
                    <el-input
                        :value="`${selectedCourse.courseScheduleDetails?.currentEnrollment}/${selectedCourse.courseScheduleDetails?.maxCapacity}`"
                        disabled
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="申请日期" prop="applyDate">
                    <el-date-picker
                        v-model="adjustFormData.applyDate"
                        type="date"
                        placeholder="选择申请日期"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                        style="width: 100%"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 调整设置 + 课表 -->
      <el-row :gutter="20">
        <!-- 左侧：调整表单 -->
        <el-col :span="12">
          <el-card shadow="hover" class="h-full">
            <el-form
                ref="adjustFormRef"
                :model="adjustFormData"
                :rules="adjustFormRules"
                label-width="120px"
                class="adjust-form"
            >
              <!-- 调整范围 -->
              <div class="form-section">
                <h4 class="section-title">调整范围</h4>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="调整范围" prop="adjustmentScope">
                      <el-select
                          v-model="adjustFormData.adjustmentScope"
                          placeholder="请选择调整范围"
                          style="width: 100%"
                          @change="handleAdjustmentScopeChange"
                      >
                        <el-option value="temporary" label="临时调整"></el-option>
                        <el-option value="entire" label="调整整个周期"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="调整原因" prop="adjustmentReason">
                  <el-select
                      v-model="adjustFormData.adjustmentReason"
                      placeholder="请选择调整原因"
                      style="width: 100%"
                      clearable
                  >
                    <el-option
                        v-for="dict in reasons_adjusting_course"
                        :key="dict.value"
                        :label="dict.label"
                        :value="parseInt(dict.value)"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="详细说明" prop="adjustmentDescription">
                  <el-input
                      v-model="adjustFormData.adjustmentDescription"
                      type="textarea"
                      :rows="3"
                      placeholder="请详细说明调整原因和具体情况（至少10个字符）"
                      maxlength="500"
                      show-word-limit
                  ></el-input>
                </el-form-item>
                <el-form-item label="联系电话" prop="contactPhone">
                  <el-input
                      v-model="adjustFormData.contactPhone"
                      placeholder="请输入联系电话"
                      maxlength="11"
                      style="width: 300px"
                  ></el-input>
                </el-form-item>
              </div>

              <!-- 时间调整设置 -->
              <div class="form-section">
                <h4 class="section-title">时间调整设置</h4>
                <!-- 临时调整-教学周 -->
                <el-row :gutter="20" class="mb-2" v-if="adjustFormData.adjustmentScope === 'temporary'">
                  <el-col :span="24">
                    <el-form-item label="调整教学周" prop="tempAdjustWeeks">
                      <el-select
                          v-model="adjustFormData.tempAdjustWeeks"
                          placeholder="选择需要调整的教学周（可多选）"
                          style="width: 100%"
                          multiple
                          @change="loadScheduleData"
                      >
                        <el-option v-for="week in 20" :key="week" :label="`第${week}周`" :value="week"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <!-- 新教室 -->
                <el-row :gutter="20" class="mb-2">
                  <el-col :span="12">
                    <el-form-item label="新教室" prop="newClassroomId">
                      <el-select
                          v-model="adjustFormData.newClassroomId"
                          placeholder="请选择新的上课教室"
                          style="width: 100%"
                          @change="handleClassroomChange"
                      >
                        <el-option value="" label="不调整教室" />
                        <el-option
                            v-for="classroom in classrooms"
                            :key="classroom.id"
                            :label="`${classroom.buildingId}-${classroom.roomNumber} (${classroom.equipment || '无设备'})`"
                            :value="classroom.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <!-- 时间设置 -->
                <el-row :gutter="20" class="mb-2">
                  <el-col :span="10">
                    <el-form-item label="新上课星期" prop="newWeekDay">
                      <el-select
                          v-model="adjustFormData.newWeekDay"
                          placeholder="选择星期"
                          style="width: 100%"
                          @change="loadScheduleData"
                      >
                        <el-option v-for="option in weekDayOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="15">
                    <el-form-item label="开始时间" prop="newStartTime">
                      <el-select
                          v-model="adjustFormData.newStartTime"
                          placeholder="开始时间"
                          style="width: 100%"
                      >
                        <el-option v-for="time in timeOptions" :key="time" :label="time" :value="time"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="15">
                    <el-form-item label="结束时间" prop="newEndTime">
                      <el-select
                          v-model="adjustFormData.newEndTime"
                          placeholder="结束时间"
                          style="width: 100%"
                          @change="validateEndTime"
                      >
                        <el-option v-for="time in timeOptions" :key="time" :label="time" :value="time"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6" v-if="adjustFormData.adjustmentScope === 'entire'">
                    <el-form-item label="单双周">
                      <el-select
                          v-model="adjustFormData.newWeekType"
                          style="width: 100%"
                          @change="loadScheduleData"
                      >
                        <el-option v-for="option in weekTypeOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <!-- 整个周期-周次设置 -->
                <div v-if="adjustFormData.adjustmentScope === 'entire'">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="开始周次" prop="newStartWeek">
                        <el-input
                            v-model="adjustFormData.newStartWeek"
                            placeholder="如：1"
                            @blur="validateWeeks"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="结束周次" prop="newEndWeek">
                        <el-input
                            v-model="adjustFormData.newEndWeek"
                            placeholder="如：16"
                            @blur="validateWeeks"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>
              </div>

              <!-- 补充说明 -->
              <div class="form-section">
                <h4 class="section-title">补充说明</h4>
                <el-form-item label="备注信息">
                  <el-input
                      v-model="adjustFormData.remarks"
                      type="textarea"
                      :rows="2"
                      placeholder="其他需要说明的信息（选填）"
                      maxlength="300"
                      show-word-limit
                  ></el-input>
                </el-form-item>
              </div>

              <!-- 提示信息 -->
              <el-alert
                  title="提交须知"
                  type="info"
                  :closable="false"
                  class="mb-4"
              >
                <template #default>
                  <ul class="notice-list">
                    <li>请确保填写信息准确无误，提交后将发送给相关审核人员</li>
                    <li>紧急调课请提前电话联系教务处，确保及时处理</li>
                    <li>调课申请一般需要提前3个工作日提交</li>
                    <li>如需取消已提交的申请，请联系教务处</li>
                  </ul>
                </template>
              </el-alert>

              <!-- 操作按钮 -->
              <div class="dialog-footer mt-6">
                <el-button @click="clearSelectedCourse">取消选择</el-button>
                <el-button
                    type="primary"
                    @click="submitAdjustApplication"
                    :loading="submitting"
                >
                  {{ submitting ? '提交中...' : '提交申请' }}
                </el-button>
              </div>
            </el-form>
          </el-card>
        </el-col>

        <!-- 右侧：课表展示（核心逻辑完全复用） -->
        <el-col :span="12">
          <div class="full-width-row schedule-container h-full">
            <el-card class="schedule-card h-full">
              <div slot="header" style="text-align: center;">
                <span>课表</span>
              </div>
              <div class="card-content">
                <div class="grid-timetable">
                  <!-- 顶部星期标题 -->
                  <div class="timetable-header">
                    <div class="header-cell empty-cell"></div>
                    <div class="header-cell">星期一</div>
                    <div class="header-cell">星期二</div>
                    <div class="header-cell">星期三</div>
                    <div class="header-cell">星期四</div>
                    <div class="header-cell">星期五</div>
                    <div class="header-cell">星期六</div>
                    <div class="header-cell">星期日</div>
                  </div>

                  <!-- 课表主体 -->
                  <div class="timetable-body">
                    <!-- 左侧节次列 -->
                    <div class="lesson-index-column">
                      <div v-for="i in 10" :key="i" class="lesson-index">
                        <div class="lesson-time">{{ getTimeRange(i) }}</div>
                        <div class="lesson-number">第{{ i }}节</div>
                      </div>
                    </div>

                    <!-- 网格内容区域（数据回显核心区域） -->
                    <div class="timetable-grid">
                      <div class="grid-container">
                        <!-- 加载状态 -->
                        <div v-if="scheduleLoading" class="schedule-loading">
                          <el-icon :size="30" class="mr-2"><Loading /></el-icon>
                          <p class="mt-2">加载课表中...</p>
                        </div>

                        <!-- 无数据状态 -->
                        <div v-else-if="allCourses.length === 0" class="no-schedule">
                          <el-empty description="暂无排课数据"></el-empty>
                        </div>

                        <!-- 动态课程元素（复用样式计算与Tooltip） -->
                        <div
                            v-else
                            v-for="(course, index) in allCourses"
                            :key="`course-${index}-${course.xq}-${course.start}-${course.type}`"
                            class="course-item"
                            :style="getCourseStyle(course)"
                            :class="`course-type-${course.type}`"
                        >
                          <el-tooltip
                              effect="dark"
                              placement="top"
                              :enterable="true"
                              :content="getCourseTooltipContent(course)"
                          >
                            <div class="course-color-block">
                              <div class="course-info">
                                <div class="course-name">{{ course.title }}</div>
                                <div class="course-teacher">{{ course.teacherName || '未知教师' }}</div>
                              </div>
                            </div>
                          </el-tooltip>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 课程类型说明（样式与逻辑完全复用） -->
                <div class="schedule-legend mt-4">
                  <h5 class="legend-title">课程类型说明</h5>
                  <div class="legend-items">
                    <div class="legend-item">
                      <span class="color-marker course-type-1"></span>
                      <span class="legend-text">当前调整的课程</span>
                    </div>
                    <div class="legend-item">
                      <span class="color-marker course-type-3"></span>
                      <span class="legend-text">教师的其他课程</span>
                    </div>
                    <div class="legend-item">
                      <span class="color-marker course-type-5"></span>
                      <span class="legend-text">本班学生的其他课程</span>
                    </div>
                    <div class="legend-item">
                      <span class="color-marker course-type-4"></span>
                      <span class="legend-text">教室本周的其他课程</span>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElEmpty, ElTooltip, ElTag, ElProgress, ElMessageBox } from 'element-plus';
import { Loading } from '@element-plus/icons-vue';

// 1. 接口引入（保留基础数据接口，移除原提交接口）
import { getCourseScheduleDetailsByTeacherId00 } from "@/api/course/availability";
import { listTeacher } from "@/api/teacher/teacher.js";
import { listClassroom } from "@/api/classroom/classroom.js";
import { getResourceTimetable, getStudentTimetable } from "@/api/course/availability";

// 基础配置（新增$emit所需的proxy和路由）
const router = useRouter();
const { proxy } = getCurrentInstance();
const { reasons_adjusting_course } = proxy.useDict("reasons_adjusting_course");

// 2. 数据定义（完全保留原有结构）
// 课程选择区域数据
const courseList = ref([]);
const filteredCourseList = ref([]);
const tableLoading = ref(false);
const courseCurrentPage = ref(1);
const coursePageSize = ref(10);
const total = ref(0);
const searchKeyword = ref('');
const selectedSemester = ref('');
const selectedCourse = ref(null); // 表格选中的课程
const selectedCourses = ref([]);

// 调整申请区域数据
const teacherList = ref([]);
const classrooms = ref([]);
const submitting = ref(false);
const scheduleLoading = ref(false);
const allCourses = ref([]);
const studentTimetableData = ref([]);
const adjustFormRef = ref();

// 调整申请表单数据（完全保留）
const adjustFormData = reactive({
  courseScheduleDetailsId: '',
  classScheduleDetailedId: '',
  originalCourseId: '',
  originalClassName: '',
  originalTeacherId: '',
  originalClassroom: '',
  originalStartTime: '',
  originalEndTime: '',
  originalWeekDay: '',
  originalWeekType: '',
  originalStartWeek: '',
  originalEndWeek: '',
  adjustmentScope: '',
  newClassroomId: '',
  newStartTime: '',
  newEndTime: '',
  newWeekDay: '',
  newWeekType: 1,
  newStartWeek: '',
  newEndWeek: '',
  tempAdjustWeeks: [],
  adjustmentReason: null,
  adjustmentDescription: '',
  applicantId: '',
  contactPhone: '',
  urgentLevel: 1,
  applyDate: new Date().toISOString().split('T')[0],
  remarks: ''
});

// 调整范围切换逻辑（保留）
const handleAdjustmentScopeChange = () => {
  if (adjustFormData.adjustmentScope === 'temporary') {
    adjustFormData.newStartWeek = '';
    adjustFormData.newEndWeek = '';
  } else {
    adjustFormData.tempAdjustWeeks = [];
  }
  loadScheduleData();
};

// 3. 下拉选项（完全保留）
const weekDayOptions = [
  { value: 1, label: '周一' }, { value: 2, label: '周二' }, { value: 3, label: '周三' },
  { value: 4, label: '周四' }, { value: 5, label: '周五' }, { value: 6, label: '周六' },
  { value: 7, label: '周日' }
];
const weekTypeOptions = [
  { value: 1, label: '每周' }, { value: 2, label: '单周' }, { value: 4, label: '双周' }
];
const timeOptions = [
  '10:00', '10:45', '10:55', '11:40', '12:10', '12:55',
  '13:05', '13:50', '15:00', '15:45', '15:55', '16:40',
  '17:10', '17:55', '18:05', '18:50', '21:00', '21:45',
  '21:55', '22:40'
];

// 4. 表单验证规则（完全保留）
const adjustFormRules = {
  adjustmentScope: [
    { required: true, message: '请选择调整范围', trigger: 'change' }
  ],
  adjustmentReason: [
    { required: true, message: '请选择调整原因', trigger: 'change' }
  ],
  adjustmentDescription: [
    { required: true, message: '请输入详细说明', trigger: 'blur' },
    { min: 10, message: '详细说明至少10个字符', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  tempAdjustWeeks: [
    {
      required: (() => adjustFormData.adjustmentScope === 'temporary'),
      message: '请选择调整教学周',
      trigger: 'change'
    }
  ],
  newWeekDay: [
    {
      required: true,
      message: '请选择新的上课星期',
      trigger: 'change'
    }
  ],
  newStartTime: [
    {
      required: true,
      message: '请选择开始时间',
      trigger: 'change'
    }
  ],
  newEndTime: [
    {
      required: true,
      message: '请选择结束时间',
      trigger: 'change'
    }
  ],
  newStartWeek: [
    {
      required: (() => adjustFormData.adjustmentScope === 'entire'),
      validator: (rule, value, callback) => {
        if (!value) callback(new Error('请输入开始周次'));
        else if (!/^\d+$/.test(value)) callback(new Error('请输入有效的周次数字'));
        else callback();
      },
      trigger: 'blur'
    }
  ],
  newEndWeek: [
    {
      required: (() => adjustFormData.adjustmentScope === 'entire'),
      validator: (rule, value, callback) => {
        if (!value) callback(new Error('请输入结束周次'));
        else if (!/^\d+$/.test(value)) callback(new Error('请输入有效的周次数字'));
        else callback();
      },
      trigger: 'blur'
    }
  ]
};

// 5. 学生课表处理（完全保留）
const transformStudentTimetable = (weekdays) => {
  studentTimetableData.value = [];
  weekdays.forEach(weekday => {
    const xq = weekday.dayOfWeek;
    weekday.timeSlots.forEach(slot => {
      slot.courses.forEach(course => {
        const start = parseInt(course.startLesson);
        const end = parseInt(course.endLesson);
        if (!isNaN(start) && !isNaN(end) && start >= 1 && end <= 10) {
          studentTimetableData.value.push({
            xq: xq,
            start: start,
            end: end,
            title: course.title || "学生其他课程",
            addr: course.location || "",
            skjc: `${start}-${end}节`,
            jxbzc: course.extraInfo?.weekType || '',
            num: slot.timePeriod || '未知时段',
            type: 5
          });
        }
      });
    });
  });
};

const fetchStudentTimetable = async () => {
  const courseScheduleDetailsId = selectedCourse.value?.courseScheduleDetails?.id;
  if (!courseScheduleDetailsId) {
    console.warn("未获取到课程详情ID，无法加载学生课表");
    return;
  }

  try {
    const response = await getStudentTimetable(courseScheduleDetailsId);
    if (response.code === 200) {
      const studentData = response.params?.data;
      if (studentData?.weekdays && Array.isArray(studentData.weekdays)) {
        transformStudentTimetable(studentData.weekdays);
      }
    }
  } catch (error) {
    console.error("获取学生课表失败:", error);
  }
};

// 6. 课表核心方法（完全保留）
const getTeacherList = async () => {
  try {
    const response = await listTeacher();
    if (response && response.code === 200 && Array.isArray(response.rows)) {
      teacherList.value = response.rows;
    } else {
      ElMessage.warning('获取教师数据失败');
    }
  } catch (error) {
    ElMessage.error('获取教师列表时发生错误');
    console.error('教师列表接口异常:', error);
  }
};

const getClassroomList = async () => {
  try {
    const response = await listClassroom({});
    if (response && response.code === 200 && Array.isArray(response.rows)) {
      classrooms.value = response.rows;
      const originalClassroomId = selectedCourse.value?.courseScheduleDetails?.classroomId;
      if (originalClassroomId && !adjustFormData.newClassroomId) {
        adjustFormData.newClassroomId = originalClassroomId;
      }
    } else {
      ElMessage.warning('获取教室数据失败');
    }
  } catch (error) {
    ElMessage.error('获取教室列表时发生错误');
    console.error('教室列表接口异常:', error);
  }
};

const handleClassroomChange = () => {
  loadScheduleData();
};

const loadScheduleData = async () => {
  allCourses.value = [];
  scheduleLoading.value = true;

  try {
    const allScheduleData = [];
    const courseDetails = selectedCourse.value?.courseScheduleDetails;
    const academicYear = courseDetails?.academicYear ?? 0;
    const originalTeacherId = courseDetails?.teacherId;
    const originalClassroomId = courseDetails?.classroomId || '';

    // 确定当前选中的教室ID（不调整则用原教室）
    const selectedClassroomId = adjustFormData.newClassroomId === ''
        ? originalClassroomId
        : adjustFormData.newClassroomId;

    // 加载教师、教室课表
    if (originalTeacherId) {
      const teacherData = await fetchResourceSchedule(originalTeacherId, academicYear, 3);
      allScheduleData.push(...teacherData);
    }
    if (selectedClassroomId) {
      const classroomData = await fetchResourceSchedule(selectedClassroomId, academicYear, 4);
      allScheduleData.push(...classroomData);
    }

    // 加载学生课表
    await fetchStudentTimetable();

    // 数据合并与处理
    const transformedResourceData = transformToGridFormat(allScheduleData);
    const mergedData = [...transformedResourceData, ...studentTimetableData.value];
    const dataWithOverlap = processCoursesWithOverlap(mergedData);
    const conflictHandledData = handleConflictingCourses(dataWithOverlap);

    // 排序
    conflictHandledData.sort((a, b) => {
      if (a.xq !== b.xq) return a.xq - b.xq;
      if (a.start !== b.start) return a.start - b.start;
      return a.overlapIndex - b.overlapIndex;
    });

    allCourses.value = conflictHandledData;
  } catch (error) {
    ElMessage.error('获取课表数据失败，请稍后重试');
    console.error('课表加载异常:', error);
  } finally {
    scheduleLoading.value = false;
  }
};

// 重叠课程处理（保留）
const getOverlappingGroups = (courses) => {
  const timeSlotMap = {};
  courses.forEach(course => {
    const key = `${course.xq}-${course.start}-${course.end}`;
    if (!timeSlotMap[key]) timeSlotMap[key] = [];
    timeSlotMap[key].push(course);
  });
  return timeSlotMap;
};

const processCoursesWithOverlap = (courses) => {
  const timeSlotMap = getOverlappingGroups(courses);
  return courses.map(course => {
    const key = `${course.xq}-${course.start}-${course.end}`;
    const group = timeSlotMap[key];
    return {
      ...course,
      overlapTotal: group.length,
      overlapIndex: group.findIndex(item => item === course)
    };
  });
};

// 7. 课程选择区域方法（完全保留）
const loadCourses = async () => {
  tableLoading.value = true;
  try {
    const response = await getCourseScheduleDetailsByTeacherId00();
    let courseData = [];
    if (response && Array.isArray(response)) courseData = response;
    else if (response && response.data && Array.isArray(response.data)) courseData = response.data;
    else if (response && Array.isArray(response.rows)) courseData = response.rows;

    if (courseData.length > 0) {
      const formattedCourses = [];
      courseData.forEach(item => {
        if (!item.courseScheduleDetails || !item.classScheduleDetailedList) return;
        const baseInfo = item.courseScheduleDetails;
        const scheduleDetails = item.classScheduleDetailedList;
        const academicYear = baseInfo.academicYear || baseInfo.grade;
        const academicYearText = academicYear ? `${academicYear}-${academicYear + 1}学年` : '未知学年';
        const semesterText = baseInfo.semester === 1 ? '第一学期' : '第二学期';
        const currentEnrollment = Number(baseInfo.currentEnrollment) || 0;
        const maxCapacity = Number(baseInfo.maxCapacity) || 0;
        const enrollmentRate = maxCapacity > 0 ? Math.round((currentEnrollment / maxCapacity) * 100) : 0;
        const classroom = baseInfo.classroom || '未知教室';
        const displayClassroom = classroom.length > 20 ? `教室ID: ${classroom.slice(0, 8)}...` : classroom;

        scheduleDetails.forEach(detail => {
          formattedCourses.push({
            courseScheduleDetails: baseInfo,
            classScheduleDetailedList: scheduleDetails,
            currentDetail: detail,
            id: baseInfo.id,
            courseId: baseInfo.courseId || '',
            courseName: (baseInfo.className || '').split('-')[0] || '未知课程',
            className: baseInfo.className || '未知班级',
            academicYear: academicYearText,
            semesterText,
            semesterNum: baseInfo.semester || 0,
            weekDay: detail.weekDay,
            startTime: detail.startTime || '未知',
            endTime: detail.endTime || '未知',
            weekType: detail.weekType,
            classroom: displayClassroom,
            currentEnrollment,
            maxCapacity,
            enrollmentRate,
            department: baseInfo.department || '未知学院',
            status: baseInfo.status || 1,
            lessonCount: detail.lessonCount || 0,
            scheduleId: detail.id || ''
          });
        });
      });
      courseList.value = formattedCourses;
      total.value = formattedCourses.length;
      handleFilterChange();
      if (formattedCourses.length > 0 && filteredCourseList.value.length === 0) {
        ElMessage.info('未找到匹配筛选条件的课程，请调整搜索关键词或学期');
      }
    } else {
      ElMessage.info('当前账号暂无授课课程数据');
      courseList.value = [];
      filteredCourseList.value = [];
      total.value = 0;
    }
  } catch (error) {
    ElMessage.error('加载课程列表失败，请刷新页面重试');
    console.error('课程接口异常:', error);
  } finally {
    tableLoading.value = false;
  }
};

const handleSearch = () => {
  courseCurrentPage.value = 1;
  handleFilterChange();
};

const handleFilterChange = () => {
  let result = [...courseList.value];
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    result = result.filter(course =>
        course.courseName.toLowerCase().includes(keyword) ||
        (course.courseId && course.courseId.toLowerCase().includes(keyword)) ||
        course.className.toLowerCase().includes(keyword) ||
        (course.department && course.department.toLowerCase().includes(keyword))
    );
  }
  if (selectedSemester.value) {
    const [year, semester] = selectedSemester.value.split('-');
    result = result.filter(course =>
        course.academicYear.includes(year) &&
        (semester === '1' ? course.semesterText.includes('第一') : course.semesterText.includes('第二'))
    );
  }
  filteredCourseList.value = result;
  total.value = result.length;
};

const handleCourseSizeChange = (val) => {
  coursePageSize.value = val;
  courseCurrentPage.value = 1;
};

const handleCourseCurrentChange = (val) => {
  courseCurrentPage.value = val;
};

const handleSelectionChange = (val) => {
  selectedCourses.value = val;
};

// 选择课程初始化表单（保留）
const selectCourse = (course) => {
  selectedCourse.value = course;
  const courseDetails = course.courseScheduleDetails || {};
  const schedule = course.currentDetail || {};
  // 初始化表单基础数据
  adjustFormData.courseScheduleDetailsId = courseDetails.id;
  adjustFormData.classScheduleDetailedId = schedule.id;
  adjustFormData.originalCourseId = courseDetails.courseId;
  adjustFormData.originalClassName = courseDetails.className;
  adjustFormData.originalTeacherId = courseDetails.teacherId;
  adjustFormData.originalClassroom = courseDetails.classroom;
  adjustFormData.originalStartWeek = courseDetails.startWeek;
  adjustFormData.originalEndWeek = courseDetails.endWeek;
  adjustFormData.originalWeekType = courseDetails.weekType;
  adjustFormData.originalWeekDay = schedule.weekDay;
  adjustFormData.originalStartTime = schedule.startTime;
  adjustFormData.originalEndTime = schedule.endTime;

  // 加载依赖数据
  Promise.all([getTeacherList(), getClassroomList()])
      .then(() => fetchStudentTimetable())
      .then(() => loadScheduleData())
      .catch(error => ElMessage.error(`数据初始化失败：${error.message}`));
};

const showCourseDetail = (course) => {
  ElMessage.info(`课程《${course.courseName}》详情：${JSON.stringify(course.courseScheduleDetails, null, 2)}`);
};

const clearSelectedCourse = () => {
  selectedCourse.value = null;
  if (adjustFormRef.value) adjustFormRef.value.resetFields();
  adjustFormData.tempAdjustWeeks = [];
  adjustFormData.adjustmentScope = '';
  allCourses.value = [];
};

// 8. 课表工具方法（完全保留）
const buildCurrentAdjustCourse = (courseDetails) => {
  const newWeekDay = adjustFormData.newWeekDay || courseDetails.weekDay || 1;
  const newStartTime = adjustFormData.newStartTime || courseDetails.classScheduleDetailedList?.[0]?.startTime || '10:00';
  const newEndTime = adjustFormData.newEndTime || courseDetails.classScheduleDetailedList?.[0]?.endTime || '10:45';

  return {
    xq: newWeekDay,
    start: getLessonNumByTime(newStartTime),
    end: getLessonNumByTime(newEndTime),
    title: `当前调整：${courseDetails.className || '未知课程'}`,
    addr: adjustFormData.newClassroomId
        ? getClassroomName(adjustFormData.newClassroomId)
        : courseDetails.classroom || '无地点',
    skjc: `${getLessonNumByTime(newStartTime)}-${getLessonNumByTime(newEndTime)}节`,
    jxbzc: adjustFormData.newWeekType === 2 ? '单周' : adjustFormData.newWeekType === 4 ? '双周' : '每周',
    num: `${adjustFormData.newStartWeek || courseDetails.startWeek}-${adjustFormData.newEndWeek || courseDetails.endWeek}周`,
    type: 1,
    teacherName: getTeacherName(courseDetails.teacherId),
    isCurrent: true
  };
};

const getLessonNumByTime = (time) => {
  if (!time) return 1;
  const timeMap = {
    '10:00': 1, '10:45': 1, '10:55': 2, '11:40': 2,
    '12:10': 3, '12:55': 3, '13:05': 4, '13:50': 4,
    '15:00': 5, '15:45': 5, '15:55': 6, '16:40': 6,
    '17:10': 7, '17:55': 7, '18:05': 8, '18:50': 8,
    '21:00': 9, '21:45': 9, '21:55': 10, '22:40': 10
  };
  return timeMap[time] || 1;
};

const fetchResourceSchedule = async (resourceId, academicYear, type) => {
  if (!resourceId) {
    console.warn('resourceId缺失');
    return [];
  }
  try {
    const response = await getResourceTimetable(resourceId, academicYear);
    if (response.code === 200) {
      const weekdays = response.data?.weekdays || response.params?.data?.weekdays;
      if (Array.isArray(weekdays)) {
        return weekdays.map(weekday => ({ ...weekday, type }));
      }
    }
    console.warn('接口返回格式异常:', response);
    return [];
  } catch (error) {
    console.error('接口调用失败:', error);
    return [];
  }
};

const transformToGridFormat = (rawData) => {
  const transformed = [];
  const currentCourseId = selectedCourse.value?.courseScheduleDetails?.id;

  rawData.forEach(weekday => {
    const xq = weekday.dayOfWeek;
    if (!weekday.timeSlots || !Array.isArray(weekday.timeSlots)) return;

    weekday.timeSlots.forEach(slot => {
      if (!slot.courses || !Array.isArray(slot.courses)) return;

      slot.courses.forEach(course => {
        const isCurrentCourse = course.id === currentCourseId;
        const start = Number(course.startLesson);
        const end = Number(course.endLesson);

        if (isNaN(start) || isNaN(end) || start < 1 || end > 10 || start > end) return;

        transformed.push({
          xq: xq,
          start: start,
          end: end,
          title: course.title || '未命名课程',
          skjc: `${start}-${end}节`,
          addr: course.location || '无地点',
          jxbzc: course.extraInfo?.isAvailable === 0 ? '已占用' : '可用',
          num: slot.timePeriod || '未知时段',
          type: isCurrentCourse ? 1 : (weekday.type || 3)
        });
      });
    });
  });
  return transformed;
};

const getTimeRange = (lessonNum) => {
  const timeRanges = [
    '10:00-10:45', '10:55-11:40', '12:10-12:55', '13:05-13:55',
    '15:00-15:45', '15:55-16:40', '17:10-17:55', '18:05-18:50',
    '20:00-20:45', '20:55-21:40'
  ];
  return timeRanges[lessonNum - 1] || '';
};

const getCurrentAdjustCourse = (courses) => {
  return courses.find(course => course.type === 1) || null;
};

const isConflicting = (currentCourse, otherCourse) => {
  return currentCourse.start <= otherCourse.end && currentCourse.end >= otherCourse.start;
};

const handleConflictingCourses = (allCourses) => {
  const currentCourse = getCurrentAdjustCourse(allCourses);
  if (!currentCourse) return allCourses;

  const processedCourses = [];
  allCourses.forEach(course => {
    if (course.type === 1) {
      processedCourses.push(course);
      return;
    }

    if (!isConflicting(currentCourse, course)) {
      processedCourses.push(course);
      return;
    }

    const { start: currStart, end: currEnd } = currentCourse;
    const { start: otherStart, end: otherEnd } = course;

    if (otherStart >= currStart && otherEnd <= currEnd) return;
    if (otherStart < currStart && otherEnd <= currEnd && otherEnd >= currStart) {
      processedCourses.push({ ...course, start: otherStart, end: currStart - 1 });
      return;
    }
    if (otherStart >= currStart && otherStart <= currEnd && otherEnd > currEnd) {
      processedCourses.push({ ...course, start: currEnd + 1, end: otherEnd });
      return;
    }
    if (otherStart < currStart && otherEnd > currEnd) {
      processedCourses.push({ ...course, start: otherStart, end: currStart - 1 });
      processedCourses.push({ ...course, start: currEnd + 1, end: otherEnd });
      return;
    }
  });

  return processedCourses;
};

const getCourseStyle = (course) => {
  const colIndex = course.xq - 1;
  const rowIndex = course.start - 1;
  const rowSpan = course.end - course.start + 1;
  const zIndex = course.type === 1 ? 10 : 1;
  const totalOverlaps = course.overlapTotal || 1;
  const baseWidth = 100 / totalOverlaps;
  const startPercent = (course.overlapIndex || 0) * baseWidth;

  return {
    gridRow: `${rowIndex + 1} / span ${rowSpan}`,
    gridColumn: `${colIndex + 1}`,
    zIndex: zIndex,
    width: `${baseWidth}%`,
    left: `${startPercent}%`
  };
};

const getCourseTooltipContent = (course) => {
  return `
    <div style="text-align: left; padding: 5px;">
      <div><strong>${course.title}</strong></div>
      <div>节次：${course.skjc}</div>
      <div>地点：${course.addr}</div>
      <div>周次：${course.num}</div>
      <div>${course.jxbzc}</div>
    </div>
  `;
};

// 9. 表单验证辅助方法（保留）
const validateEndTime = () => {
  if (adjustFormData.newStartTime && adjustFormData.newEndTime && adjustFormData.newStartTime >= adjustFormData.newEndTime) {
    ElMessage.warning('结束时间必须晚于开始时间');
    adjustFormData.newEndTime = '';
  }
};

const validateWeeks = () => {
  if (adjustFormData.newStartWeek && adjustFormData.newEndWeek) {
    const start = parseInt(adjustFormData.newStartWeek);
    const end = parseInt(adjustFormData.newEndWeek);
    if (start > end) {
      ElMessage.warning('结束周次必须大于等于开始周次');
      adjustFormData.newEndWeek = '';
    }
  }
};

// 10. 核心修改：提交逻辑（改为emit数据给父组件）
const submitAdjustApplication = async () => {
  if (!adjustFormRef.value) return;
  try {
    // 1. 表单验证
    await adjustFormRef.value.validate();
    // 2. 确认对话框
    await confirmAdjustment();
    // 3. 加载状态
    submitting.value = true;

    // 4. 整合提交数据（与原接口数据结构一致）
    const courseDetails = selectedCourse.value?.courseScheduleDetails || {};
    const originalSchedule = selectedCourse.value?.classScheduleDetailedList?.[0] || {};
    const originalClassroomId = courseDetails.classroomId || '';
    const originalClassroomName = courseDetails.classroom || '未知教室';

    // 处理教室信息（不调整则用原教室）
    let finalClassroomId, finalClassroomName;
    if (adjustFormData.newClassroomId === '') {
      finalClassroomId = originalClassroomId;
      finalClassroomName = originalClassroomName;
    } else {
      const selectedClassroom = classrooms.value.find(c => c.id === adjustFormData.newClassroomId) || {};
      finalClassroomId = selectedClassroom.id || originalClassroomId;
      finalClassroomName = `${selectedClassroom.buildingId}-${selectedClassroom.roomNumber}` || originalClassroomName;
    }

    // 构建完整提交数据（包含原接口所需的所有字段）
    const submitData = {
      // 基础表单数据
      adjustFormData: { ...adjustFormData },
      // 课程调整记录（原adjustmentRecord）
      adjustmentRecord: {
        courseScheduleDetailsId: courseDetails.id,
        classScheduleDetailedId: originalSchedule.id,
        originalCourseId: courseDetails.courseId,
        originalClassName: courseDetails.className,
        originalTeacherId: courseDetails.teacherId,
        originalClassroom: originalClassroomName,
        originalClassroomId: originalClassroomId,
        originalStartTime: originalSchedule.startTime,
        originalEndTime: originalSchedule.endTime,
        originalWeekDay: originalSchedule.weekDay,
        originalWeekType: courseDetails.weekType,
        originalStartWeek: courseDetails.startWeek,
        originalEndWeek: courseDetails.endWeek,
        adjustmentType: 'time',
        adjustmentScope: adjustFormData.adjustmentScope,
        adjustmentReason: adjustFormData.adjustmentReason,
        adjustmentDescription: adjustFormData.adjustmentDescription,
        applicantId: adjustFormData.applicantId || '',
        contactPhone: adjustFormData.contactPhone,
        urgentLevel: adjustFormData.urgentLevel,
        applyDate: adjustFormData.applyDate,
        remarks: adjustFormData.remarks,
        approvalStatus: '0',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        newClassroomId: finalClassroomId,
        newClassroom: finalClassroomName,
        newStartTime: adjustFormData.newStartTime || originalSchedule.startTime,
        newEndTime: adjustFormData.newEndTime || originalSchedule.endTime,
        newWeekDay: adjustFormData.newWeekDay || originalSchedule.weekDay,
        newWeekType: adjustFormData.newWeekType || courseDetails.weekType,
        newStartWeek: adjustFormData.newStartWeek ? parseInt(adjustFormData.newStartWeek) : courseDetails.startWeek,
        newEndWeek: adjustFormData.newEndWeek ? parseInt(adjustFormData.newEndWeek) : courseDetails.endWeek,
        tempAdjustWeeks: adjustFormData.tempAdjustWeeks,
        tempAdjustDate: ''
      },
      // 课程详情更新数据（原scheduleDetailsToUpdate）
      scheduleDetailsToUpdate: adjustFormData.adjustmentScope === 'entire'
          ? {
            id: courseDetails.id,
            className: courseDetails.className,
            teacherId: courseDetails.teacherId,
            classroom: finalClassroomName,
            classroomId: finalClassroomId,
            startWeek: adjustFormData.newStartWeek ? parseInt(adjustFormData.newStartWeek) : courseDetails.startWeek,
            endWeek: adjustFormData.newEndWeek ? parseInt(adjustFormData.newEndWeek) : courseDetails.endWeek,
            weekType: adjustFormData.newWeekType || courseDetails.weekType,
            classScheduleDetailedList: [
              {
                id: originalSchedule.id,
                weekDay: adjustFormData.newWeekDay || originalSchedule.weekDay,
                startTime: adjustFormData.newStartTime || originalSchedule.startTime,
                endTime: adjustFormData.newEndTime || originalSchedule.endTime,
                lessonCount: originalSchedule.lessonCount
              }
            ]
          }
          : null
    };

    // 5. 关键：emit数据给父组件（JSON.stringify确保数据格式统一）
    proxy.$emit("handleBizBtn", JSON.stringify(submitData));

    // 6. 提交成功提示
    ElMessage.success('课程调整申请提交成功！');
    // 可根据需求决定是否重置表单（此处保留重置逻辑）
    clearSelectedCourse();

  } catch (error) {
    // 错误处理（验证失败/用户取消确认）
    if (error !== 'cancel') { // 排除用户取消确认的情况
      console.error('提交失败:', error);
      ElMessage.error(error.message || '提交失败，请检查填写信息');
    }
  } finally {
    // 关闭加载状态
    submitting.value = false;
  }
};

// 确认对话框（保留）
const confirmAdjustment = () => {
  return new Promise((resolve, reject) => {
    const currentClassroom = getClassroomName(adjustFormData.newClassroomId);
    ElMessageBox.confirm(
        `
      <div style="text-align: left;">
        <p>确认提交课程调整申请？</p>
        <p>调整范围：${adjustFormData.adjustmentScope === 'temporary' ? '临时调整' : '调整整个周期'}</p>
        <p>新教室：${currentClassroom}</p>
        <p>新时间：${getWeekDay(adjustFormData.newWeekDay)} ${adjustFormData.newStartTime}-${adjustFormData.newEndTime}</p>
      </div>
      `,
        '确认提交',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info',
          dangerouslyUseHTMLString: true
        }
    ).then(() => resolve()).catch(() => reject('cancel'));
  });
};

// 11. 通用工具方法（保留）
const getWeekDay = (day) => {
  const weekdays = ['', '周一', '周二', '周三', '周四', '周五', '周六', '周日'];
  return weekdays[day] || '未知';
};

const getOriginalTimeText = () => {
  const schedule = selectedCourse.value?.classScheduleDetailedList?.[0] || {};
  const originalClassroom = selectedCourse.value?.courseScheduleDetails?.classroom || '未知教室';
  if (!schedule.weekDay) return '';
  return `${getWeekDay(schedule.weekDay)} ${schedule.startTime}-${schedule.endTime}（教室：${originalClassroom}）`;
};

const getTeacherName = (teacherId) => {
  if (!teacherId) return '未知教师';
  const teacher = teacherList.value.find(t => t.uuid === teacherId);
  return teacher ? teacher.name : '未知教师';
};

const getClassroomName = (classroomId) => {
  if (!classroomId && classroomId !== 0) return '不调整教室';
  const selectedClassroom = classrooms.value.find(c => c.id === classroomId);
  return selectedClassroom ? `${selectedClassroom.buildingId}-${selectedClassroom.roomNumber}` : '未知教室';
};

// 12. 新增：对齐其他表单的getFromData方法（方便父组件主动获取数据）
const getFromData = () => {
  return new Promise((resolve, reject) => {
    try {
      // 构建与submitAdjustApplication一致的提交数据
      const courseDetails = selectedCourse.value?.courseScheduleDetails || {};
      const originalSchedule = selectedCourse.value?.classScheduleDetailedList?.[0] || {};
      const originalClassroomId = courseDetails.classroomId || '';
      const originalClassroomName = courseDetails.classroom || '未知教室';

      let finalClassroomId, finalClassroomName;
      if (adjustFormData.newClassroomId === '') {
        finalClassroomId = originalClassroomId;
        finalClassroomName = originalClassroomName;
      } else {
        const selectedClassroom = classrooms.value.find(c => c.id === adjustFormData.newClassroomId) || {};
        finalClassroomId = selectedClassroom.id || originalClassroomId;
        finalClassroomName = `${selectedClassroom.buildingId}-${selectedClassroom.roomNumber}` || originalClassroomName;
      }

      const submitData = {
        adjustFormData: { ...adjustFormData },
        adjustmentRecord: {
          courseScheduleDetailsId: courseDetails.id,
          classScheduleDetailedId: originalSchedule.id,
          originalCourseId: courseDetails.courseId,
          originalClassName: courseDetails.className,
          originalTeacherId: courseDetails.teacherId,
          originalClassroom: originalClassroomName,
          originalClassroomId: originalClassroomId,
          originalStartTime: originalSchedule.startTime,
          originalEndTime: originalSchedule.endTime,
          originalWeekDay: originalSchedule.weekDay,
          originalWeekType: courseDetails.weekType,
          originalStartWeek: courseDetails.startWeek,
          originalEndWeek: courseDetails.endWeek,
          adjustmentType: 'time',
          adjustmentScope: adjustFormData.adjustmentScope,
          adjustmentReason: adjustFormData.adjustmentReason,
          adjustmentDescription: adjustFormData.adjustmentDescription,
          applicantId: adjustFormData.applicantId || '',
          contactPhone: adjustFormData.contactPhone,
          urgentLevel: adjustFormData.urgentLevel,
          applyDate: adjustFormData.applyDate,
          remarks: adjustFormData.remarks,
          approvalStatus: '0',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
          newClassroomId: finalClassroomId,
          newClassroom: finalClassroomName,
          newStartTime: adjustFormData.newStartTime || originalSchedule.startTime,
          newEndTime: adjustFormData.newEndTime || originalSchedule.endTime,
          newWeekDay: adjustFormData.newWeekDay || originalSchedule.weekDay,
          newWeekType: adjustFormData.newWeekType || courseDetails.weekType,
          newStartWeek: adjustFormData.newStartWeek ? parseInt(adjustFormData.newStartWeek) : courseDetails.startWeek,
          newEndWeek: adjustFormData.newEndWeek ? parseInt(adjustFormData.newEndWeek) : courseDetails.endWeek,
          tempAdjustWeeks: adjustFormData.tempAdjustWeeks,
          tempAdjustDate: ''
        },
        scheduleDetailsToUpdate: adjustFormData.adjustmentScope === 'entire'
            ? {
              id: courseDetails.id,
              className: courseDetails.className,
              teacherId: courseDetails.teacherId,
              classroom: finalClassroomName,
              classroomId: finalClassroomId,
              startWeek: adjustFormData.newStartWeek ? parseInt(adjustFormData.newStartWeek) : courseDetails.startWeek,
              endWeek: adjustFormData.newEndWeek ? parseInt(adjustFormData.newEndWeek) : courseDetails.endWeek,
              weekType: adjustFormData.newWeekType || courseDetails.weekType,
              classScheduleDetailedList: [
                {
                  id: originalSchedule.id,
                  weekDay: adjustFormData.newWeekDay || originalSchedule.weekDay,
                  startTime: adjustFormData.newStartTime || originalSchedule.startTime,
                  endTime: adjustFormData.newEndTime || originalSchedule.endTime,
                  lessonCount: originalSchedule.lessonCount
                }
              ]
            }
            : null
      };
      resolve(JSON.stringify(submitData));
    } catch (error) {
      reject(error);
    }
  });
};

// 13. 表单验证方法（对齐学籍异动表单，方便父组件调用）
const handleValidate = () => {
  return new Promise((resolve, reject) => {
    if (!adjustFormRef.value) {
      reject(new Error('表单引用不存在'));
      return;
    }
    adjustFormRef.value.validate((valid) => {
      if (!valid) {
        reject(new Error('表单验证失败，请检查必填项'));
        return;
      }
      // 额外校验：临时调整需选择教学周
      if (adjustFormData.adjustmentScope === 'temporary' && adjustFormData.tempAdjustWeeks.length === 0) {
        ElMessage.warning('临时调整需选择至少一个教学周');
        reject(new Error('临时调整需选择教学周'));
        return;
      }
      // 额外校验：结束时间需晚于开始时间
      if (adjustFormData.newStartTime && adjustFormData.newEndTime && adjustFormData.newStartTime >= adjustFormData.newEndTime) {
        ElMessage.warning('结束时间必须晚于开始时间');
        reject(new Error('结束时间无效'));
        return;
      }
      resolve(true);
    });
  });
};

// 14. 暴露方法（对齐学籍异动表单，供父组件调用）
defineExpose({
  handleValidate,
  getFromData
});

// 15. 页面初始化：加载课程列表
onMounted(() => {
  loadCourses();
});
</script>
<style scoped lang="scss">
// 完全复用原样式，确保课表显示效果一致
// 基础布局样式
.app-container {
  padding: 15px;
}

// 课程选择区域样式
::v-deep .el-card__body {
  padding: 20px;
}

::v-deep .el-table__cell {
  padding: 12px 0;
}

::v-deep .el-card {
  transition: all 0.3s ease;
}

::v-deep .el-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

// 调整申请区域样式
.adjust-container {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px dashed #e0e0e0;
}

.adjust-form {
  .form-section {
    margin-bottom: 24px;
    padding-bottom: 12px;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 16px;
      padding-bottom: 8px;
      border-bottom: 2px solid #E4E7ED;
    }
  }
}

.notice-list {
  margin: 0;
  padding-left: 16px;

  li {
    margin-bottom: 4px;
    color: #606266;
    font-size: 13px;
  }
}

.dialog-footer {
  text-align: right;

  .el-button {
    margin-left: 12px;
  }
}

// 课表区域样式（核心样式完全复用）
.h-full {
  height: 100%;
  min-height: 100%;
}

.schedule-container {
  width: 100%;
  height: 100%;
}

.schedule-card {
  height: 100%;
  min-height: 800px;

  .card-content {
    padding: 10px;
    height: calc(100% - 56px);
    overflow-y: auto;
  }
}

.grid-timetable {
  width: 100%;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: hidden;
  background-color: #ffffff;
}

.timetable-header {
  display: flex;
  border-bottom: 1px solid #e8e8e8;
  background-color: #f5f7fa;
}

.header-cell {
  flex: 1;
  padding: 8px 0;
  text-align: center;
  font-weight: bold;
  border-right: 1px solid #e8e8e8;
  font-size: 12px;

  &:last-child {
    border-right: none;
  }
}

.empty-cell {
  flex: 0 0 80px;
  border-right: 1px solid #e8e8e8;
}

.timetable-body {
  display: flex;
}

.lesson-index-column {
  width: 80px;
  border-right: 1px solid #e8e8e8;
  background-color: #f5f7fa;
}

.lesson-index {
  height: 60px;
  border-bottom: 1px solid #e8e8e8;
  padding: 5px;
  box-sizing: border-box;

  &:last-child {
    border-bottom: none;
  }
}

.lesson-time {
  font-size: 11px;
  color: #666;
  text-align: center;
}

.lesson-number {
  font-size: 12px;
  font-weight: bold;
  text-align: center;
  margin-top: 3px;
}

.timetable-grid {
  flex: 1;
  overflow: hidden;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-template-rows: repeat(10, 60px);
  grid-gap: 1px;
  background-color: #e8e8e8;
  height: 600px;
  position: relative;
}

.course-item {
  position: relative;
  height: 100%;
  padding: 0;
  border-radius: 3px;
  overflow: hidden;
  cursor: pointer;
  box-sizing: border-box;
  transition: all 0.2s;

  &:hover {
    transform: scale(1.02);
    z-index: 20 !important;
  }

  .course-info {
    padding: 4px 6px;
    font-size: 12px;
    line-height: 1.3;
    height: 100%;
    box-sizing: border-box;
    overflow: hidden;
  }

  .course-name {
    font-weight: 500;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }

  .course-teacher, .course-room {
    font-size: 11px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
}
.course-color-block {
  width: 100%;
  height: 100%;
  border-radius: 3px;
}

.schedule-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.no-schedule {
  padding: 40px 0;
  text-align: center;
  color: #909399;

  .empty-icon {
    font-size: 48px;
    margin-bottom: 16px;
    color: #c0c4cc;
  }
}

.schedule-legend {
  padding: 10px 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
  margin-bottom: 15px;
}

.legend-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  padding-bottom: 5px;
  border-bottom: 1px dashed #e0e0e0;
}

.legend-items {
  display: flex;
  flex-wrap: wrap;
  gap: 12px 20px;
}

.legend-item {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #666;
}

.color-marker {
  display: inline-block;
  width: 16px;
  height: 16px;
  border-radius: 3px;
  margin-right: 6px;
  border: 1px solid rgba(0,0,0,0.1);
}

// 课程类型颜色定义
.course-type-1 {
  background-color: rgba(103, 194, 58, 0.85);
  border: 2px solid #67c23a;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
}

.course-type-2 {
  background-color: rgba(230, 162, 60, 0.85);
  border: 2px solid #e6a23c;
  box-shadow: 0 2px 8px rgba(230, 162, 60, 0.3);
}

.course-type-3 {
  background-color: rgba(64, 158, 255, 0.85);
  border: 2px solid #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  color: white;
}

.course-type-4 {
  background-color: rgba(245, 158, 11, 0.85);
  border: 2px solid #f59e0b;
  box-shadow: 0 2px 8px rgba(245, 158, 11, 0.3);
}

.course-type-5 {
  background-color: rgba(160, 132, 247, 0.85);
  border: 2px solid #9f7aea;
  box-shadow: 0 2px 8px rgba(160, 132, 247, 0.3);
  color: white;
}

.course-type-6 {
  background-color: rgba(237, 100, 166, 0.85);
  border: 2px solid #ed64a6;
  box-shadow: 0 2px 8px rgba(237, 100, 166, 0.3);
  color: white;
}

.course-type-7 {
  background-color: rgba(75, 85, 99, 0.85);
  border: 2px solid #4b5563;
  box-shadow: 0 2px 8px rgba(75, 85, 99, 0.3);
  color: white;
}

// 响应式调整
@media screen and (max-width: 1200px) {
  .grid-container {
    height: 500px;
  }

  .lesson-index {
    height: 50px;
  }

  .grid-container {
    grid-template-rows: repeat(10, 50px);
  }
}

@media screen and (max-width: 768px) {
  .schedule-card {
    min-height: 600px;
  }

  .grid-container {
    height: 400px;
  }

  .lesson-index {
    height: 40px;
  }

  .grid-container {
    grid-template-rows: repeat(10, 40px);
  }

  .course-item .course-info {
    font-size: 11px;
    padding: 2px 4px;
  }
}
</style>
